#include <func.h>
#include "Log.h"

static struct {
    FILE* output;
    int level;
} log;

static const char* level_strings[] = {
    "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"
};

void log_set_output(const char* file) {
    FILE* output = fopen(file, "a");
    log.output = output;
}

void log_set_level(LogLevel level)
{
    log.level = level;
}

const char* log_level_string(LogLevel level)
{
    return level_strings[level];
}

void log_log(LogLevel level, const char* file, int line, const char* msg)
{
    time_t t = time(NULL);  // 获取当前的时间戳
    struct tm* bt = localtime(&t);  // 将时间戳转换为 `broken time`
    char timebuf[20];
    strftime(timebuf, 20, "%Y-%m-%d %H:%M:%S", bt); // 将`broken time`转换成特定格式的字符串
    if(level >= log.level) {
        fprintf(log.output, "%s %-5s %s:%d: %s\n", 
                timebuf,
                log_level_string(level),
                file,
                line,
                msg);
        fflush(log.output);
    }
}

#ifdef LOG_TEST
int main(void) 
{
    log_set_output("CloudDisk.log");

    log_set_level(LOG_TRACE);
    log_trace("test log_trace()...");
    log_debug("test log_debug()...");
    log_info("test log_info()...");
    log_warn("test log_warn()...");
    log_error("test log_error()...");
    log_fatal("test log_fatal()...");

    log_set_level(LOG_WARN);
    log_trace("test log_trace()...");
    log_debug("test log_debug()...");
    log_info("test log_info()...");
    log_warn("test log_warn()...");
    log_error("test log_error()...");
    log_fatal("test log_fatal()...");
    return 0;
}
#endif
